import json
import requests
from bs4 import BeautifulSoup

def get_bnbScan_data(tx_hash):
    # 交易网站的网址
    url=f'https://explorer.bnbchain.org/tx/{tx_hash}'

    headers = {
            'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0'
        }
    response = requests.get(url=url,headers=headers)

    if response.status_code == 200:
        data_html = response.text

        # 使用BeautifulSoup中的css选择器来提取数据
        soup = BeautifulSoup(data_html, 'html.parser')
        data = soup.find(name='script', attrs={'type': 'application/json'}).get_text()
        # 将json格式的数据转为python格式的数据
        dict_data = json.loads(data)

        # 继续获取具体数据
        dict_data = dict_data.get("props").get("initialState").get("txs").get("detail")

        print("BNB链数据爬取完成！")
        json_data = json.dumps(dict_data, indent=4)
        with open('../../data_new/bnbdata.json', 'w', encoding='utf-8') as f:
            f.write(json_data)
        return dict_data
    else:
        print(f"Error: {response.status_code}, {response.text}")
get_bnbScan_data("0xa8a75905573cce1c6781a59a5d8bc7a8bfb6c8539ca298cbf507a292091ad4b5")

